import config from './index.config'
import Taro from '@tarojs/taro';

/*****微信自动登录 *******/
const autoLogin = async (flora) => {
  const res = await Taro.login()
  // console.log("---获取code------", res.code, flora)
  const r = await flora.users.OpenIdlogin({  //openid验证
    openid: res.code,
  });
  if (r.status === 'ok') {
    getUserInfo(flora);
    return;
  }
  if (r.status === 'error') {
    Taro.removeStorageSync("access_token");
    Taro.reLaunch({
      url: "/pages/login/login",
    });
  }
}

const getUserInfo = async (flora) => {
  let that = this
  const type = Taro.getStorageSync('type')
  const personid = Taro.getStorageSync('personid')
  // console.log("personid", personid);
  var modelneme = "";
  var fieldsname = [];
  if (type == "teacher") {
    fieldsname = ['id', 'name', 'email', 'phone', 'wechat_id.id', 'roles_ids.flora_external_id']
    modelneme = 'FreshTeacher'
  } else {
    fieldsname = ['id', 'code', 'name', 'name_middle', 'name_pin_yin', 'phone',
      'email', 'id_card', 'birthday', 'age', 'sex',
      'political_status_id.code', 'political_status_id.name_lang_cn', 'wechat_id.id',
      'dormitory_id.ascription', 'dormitory_id.name', 'class', 'department_id.name']
    modelneme = 'FreshStudent'
  }
  flora.dash.dataApi.search({
    vars: {
      fields: fieldsname,
      model: modelneme,
      condition: {
        logic_operator: '&',
        children: [
          {
            leaf: {
              field: 'id',
              comparator: '=',
              value: personid,
            }
          },
        ]
      },
      limit: 10,
      offset: 0
    },
    cacheMode: 'no-cache',
  }).then((r) => {
    console.log("getUserInfo", r.result)
    let result = r.result.items[0] || {};
    // console.log("getUserInfo2", result)
    Taro.setStorageSync("userInfo", result.data)

    if (type == "teacher") {
      Taro.redirectTo({ url: '/pages/index/teacherIndex' })
    } else {
      Taro.switchTab({ url: '/pages/index/index' })
    }


  })

}




//网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams
  const { method, data, url } = requestParams
  let token = Taro.getStorageSync('access_token')//拿到本地缓存中存的token
  requestParams.header = {
    ...requestParams.header,
    token: token //将token添加到头部
  }
  return chain.proceed(requestParams).then(res => { return res })
}

Taro.addInterceptor(interceptor)

const request = async (method, url, params) => {
  //由于post请求时习惯性query参数使用params，body参数使用data，而taro只有data参数，使用contentType作为区分，因此此处需要做一个判断
  let contentType = params?.data ? 'application/json' : 'application/x-www-form-urlencoded';
  if (params) contentType = params?.headers?.contentType || contentType;
  const option = {
    method,
    isShowLoading: false,
    url: config.baseUrl + url,
    data: params && (params?.data || params?.params),
    header: {
      'content-type': contentType,
    },
    success(res) {
      if (res.statusCode == 401) {
        Taro.removeStorageSync("access_token");
        Taro.reLaunch({
          url: "/pages/login/login",
        });
      } else if (res.statusCode != 200) {
        Taro.showToast({
          title: "请求失败",
          icon: "error",
          duration: 2000,
        });
      }
      Taro.hideLoading();
    },
    error(e) {
      console.log('api', '请求接口出现问题', e);
      Taro.showToast({
        title: "请求失败",
        icon: "error",
        duration: 2000,
      });
      Taro.hideLoading();
    }
  }

  Taro.showLoading({ title: "加载中..." });
  const resp = await Taro.request(option);
  return resp;
}


const pullDevices = {};

let addPullTime = new Date().getTime();

const addPullDevice = function (page, deviceId) {
  let devices = pullDevices[page];
  if (!devices) {
    devices = [{ deviceId: deviceId, time: new Date().getTime() }];
  } else {
    const idx = devices.findIndex(d => d.deviceId == deviceId);
    if (idx >= 0) {
      devices.splice(idx, 1);
    }
    devices.push({ deviceId: deviceId, time: new Date().getTime() });
  }
  pullDevices[page] = devices;
}

const isPullDeviceExist = function (page, deviceId) {
  let deviceIds = Taro.getStorageSync('pullTask_' + page);
  return deviceIds && deviceIds.findIndex(d => d == deviceId) >= 0;
}

const removePullDevice = function (page, deviceId) {
  if (!deviceId) {
    delete pullDevices[page];
  } else {
    let devices = pullDevices[page];
    const idx = devices.findIndex(d => d.deviceId == deviceId);
    if (idx >= 0) {
      devices.splice(idx, 1);
    }
  }
}

const pullDeviceInfo = async (page, device, time) => {
  const deviceId = device.deviceId;
  const devices = pullDevices[page];
  if (!devices) {
    return;
  }
  const idx = devices.findIndex(d => d.deviceId == deviceId);
  if (idx == -1) {
    return;
  }
  const addTime = devices[idx].time;

  if (time && time < addTime) {
    return;
  }

  //登录时生成唯一客户端ID
  let clientId = Taro.getStorageSync('client_id');

  const lastTime = new Date().getTime();
  const task = Taro.request({
    url: config.baseUrl + "/device/" + deviceId + "/consumer/" + clientId + "_" + page,
    success(res) {
      if (res.statusCode == 200) {
        let msg = res.data;
        if (msg.type == "property") {
          console.log("set property,from", device.property, "to", msg.data);
          //属性更新
          for (let p in msg.data) {
            if (device.property) {
              device.property[p] = msg.data[p];
            }
          }
        } else if (msg.type == "state") {
          device.online = msg.identifier == "online";
        }
        //继续拉取
        pullDeviceInfo(page, device, lastTime);
      }
    }
  })
}

export default {
  get: (url, config) => {
    return request('GET', url, config);
  },
  post: (url, config) => {
    return request('POST', url, config);
  },
  put: (url, config) => {
    return request('PUT', url, config);
  },
  delete: (url, config) => {
    return request('DELETE', url, config);
  },
  pullDeviceInfo: (page, device) => {
    pullDeviceInfo(page, device);
  },
  addPullDevice: (page, deviceId) => {
    addPullDevice(page, deviceId);
  },
  removePullDevice: (page, deviceId) => {
    removePullDevice(page, deviceId);
  },
  autoLogin: (flora) => {
    autoLogin(flora);
  }
}